  <template>
    <view class="search-page">
      <NavBar @back="goBack"></NavBar>
      <!-- 自定义导航栏 -->
      <view class="nav-bar">
        <view class="nav-content">
          <view class="search-container">
            <view class="search-box">
              <text class="search-icon">🔍</text>
              <input class="search-input" v-model="searchKeyword" placeholder="搜索题目关键词" @input="handleSearch"
                @confirm="handleSearchConfirm" />
              <text class="clear-icon" v-if="searchKeyword" @click="clearSearch">✕</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 搜索结果列表 -->
      <scroll-view class="content" scroll-y @scrolltolower="loadMore">
        <!-- 热门搜索 -->
        <view class="hot-search" v-if="!searchKeyword">
          <view class="section-title">热门搜索</view>
          <view class="hot-tags">
            <text class="hot-tag" v-for="tag in hotTags" :key="tag" @click="searchByTag(tag)">
              {{ tag }}
            </text>
          </view>
        </view>

        <!-- 搜索结果统计 -->
        <view class="search-result-info" v-if="!loading && questions.length > 0">
          <text class="result-count">
            {{ searchKeyword ? `找到 ${total} 个相关题目` : `共 ${total} 个题目` }}
          </text>
        </view>

        <!-- 题目列表 -->
        <view class="question-list">
          <view class="question-item" v-for="item in filteredQuestions" :key="item.id" @click="goToDetail(item)">
            <!-- VIP角标 -->
            <view class="vip-badge" v-if="item.requirePremium"></view>
            <view class="question-header">
              <text class="question-title">{{ item.title }}</text>
              <view class="question-meta">
                <view class="difficulty-badge" :class="`difficulty-${item.difficulty}`">
                  {{ getDifficultyText(item.difficulty) }}
                </view>
              </view>
            </view>
            <view class="question-stats">
              <text class="publish-date">{{ item.publishDate }}</text>
              <view class="question-stats-right">
                <view class="stat-item">
                  <SvgIcon name="view" :size="16" />
                  <text class="stat-text">{{ item.viewCount || 0 }}</text>
                </view>
                <view class="stat-item" :class="{ active: item.isLiked }">
                  <SvgIcon :name="item.isLiked ? 'like2' : 'like'" :size="16" />
                  <text class="stat-text">{{ item.likes }}</text>
                </view>
                <view class="stat-item" :class="{ active: item.isFavorited }">
                  <SvgIcon :name="item.isFavorited ? 'save2' : 'save'" :size="16" />
                  <text class="stat-text">{{ item.stars }}</text>
                </view>
              </view>
            </view>
          </view>

          <!-- 加载更多 -->
          <view class="load-more" v-if="loading">
            <text class="load-more-text">加载中...</text>
          </view>

          <!-- 没有更多数据 -->
          <view class="no-more" v-if="!loading && questions.length >= total && total > 0">
            <text class="no-more-text">没有更多了</text>
          </view>
        </view>

        <!-- 空状态 -->
        <view class="empty-state" v-if="filteredQuestions.length === 0 && searchKeyword">
          <text class="empty-icon">🔍</text>
          <text class="empty-text">未找到相关题目</text>
          <text class="empty-desc">试试其他关键词吧</text>
        </view>
      </scroll-view>
    </view>
  </template>

  <script setup lang="ts">
  import { ref, computed, onMounted } from 'vue'
  import { useNavBar } from '@/hooks/useNavBar'
  import { searchInterviews, type Interview } from '@/api/interview'
  import NavBar from '@/components/NavBar.vue'
  import SvgIcon from '@/components/SvgIcon.vue'

  // 题目数据类型
  interface QuestionItem {
    id: number
    title: string
    question: string
    publishDate: string
    likes: number
    stars: number
    isLiked: boolean
    isFavorited: boolean
    difficulty: number
    categoryId: number
    viewCount: number
    requirePremium: boolean
  }

  const { navBarHeight, capsuleBottom } = useNavBar()

  // 搜索关键词
  const searchKeyword = ref('')

  // 热门标签
  const hotTags = ref([
    'Vue', '双向绑定', '组件通信', '路由', '状态管理',
    'React', 'Hooks', 'TypeScript', '性能优化'
  ])

  // 题目数据（真实接口数据）
  const questions = ref<QuestionItem[]>([])
  const loading = ref(false)
  const total = ref(0)
  const page = ref(1)
  const pageSize = ref(10)

  /**
   * 过滤后的题目列表
   */
  const filteredQuestions = computed(() => {
    return questions.value
  })

  /**
   * 加载题目列表
   */
  const loadQuestions = async (isLoadMore = false) => {
    if (loading.value) return

    loading.value = true
    try {
      // 只使用搜索接口
      const params = {
        keyword: searchKeyword.value.trim() || '', // 空字符串表示搜索所有
        page: page.value,
        pageSize: pageSize.value
      }

      console.log('请求参数:', params)
      const res = await searchInterviews(params)
      console.log('接口响应:', res)

      if (res.code === 200) {
        const newQuestions = res.data.list.map((item: any) => ({
          id: item.id,
          title: item.title || item.question,
          question: item.question,
          publishDate: formatDate(item.createTime),
          likes: item.likeCount,
          stars: item.favoriteCount,
          isLiked: item.isLiked,
          isFavorited: item.isFavorited,
          difficulty: item.difficulty,
          categoryId: item.categoryId,
          viewCount: item.viewCount,
          requirePremium: item.requirePremium || false
        }))

        if (isLoadMore) {
          questions.value = [...questions.value, ...newQuestions]
          console.log('追加数据，当前总数:', questions.value.length)
        } else {
          questions.value = newQuestions
          console.log('替换数据，当前总数:', questions.value.length)
        }

        total.value = res.data.total
        console.log('总数据量:', total.value)
      }
    } catch (error) {
      console.error('加载题目列表失败:', error)
      uni.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      })
    } finally {
      loading.value = false
    }
  }

  /**
   * 格式化日期
   */
  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  }

  /**
   * 获取难度文本
   */
  const getDifficultyText = (difficulty: number) => {
    const difficultyMap: { [key: number]: string } = {
      1: '简单',
      2: '中等',
      3: '困难',
      4: '专家'
    }
    return difficultyMap[difficulty] || '未知'
  }

  /**
   * 处理搜索输入
   */
  const handleSearch = (e: any) => {
    searchKeyword.value = e.detail.value
    // 重置分页
    page.value = 1
    // 防抖处理，避免频繁请求
    debounceSearch()
  }

  /**
   * 处理搜索确认
   */
  const handleSearchConfirm = () => {
    page.value = 1
    loadQuestions()
  }

  /**
   * 清空搜索
   */
  const clearSearch = () => {
    searchKeyword.value = ''
    page.value = 1
    loadQuestions()
  }

  /**
   * 防抖搜索
   */
  let searchTimeout: any = null
  const debounceSearch = () => {
    if (searchTimeout) {
      clearTimeout(searchTimeout)
    }
    searchTimeout = setTimeout(() => {
      loadQuestions()
    }, 300)
  }

  /**
   * 通过标签搜索
   */
  const searchByTag = (tag: string) => {
    searchKeyword.value = tag
    page.value = 1
    loadQuestions()
  }

  /**
   * 返回上一页
   */
  const goBack = () => {
    uni.navigateBack()
  }

  /**
   * 跳转到题目详情
   */
  const goToDetail = (item: QuestionItem) => {
    uni.navigateTo({
      url: `/pages/detail/detail?id=${item.id}`
    })
  }

  /**
   * 页面加载时初始化数据
   */
  onMounted(() => {
    // 获取页面参数
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const options = (currentPage as any).options || {}

    // 如果有传递的关键词，设置到搜索框并搜索
    if (options.keyword) {
      searchKeyword.value = decodeURIComponent(options.keyword)
      loadQuestions()
    } else {
      // 初始加载所有题目（空关键词搜索）
      loadQuestions()
    }
  })

  /**
   * 加载更多数据
   */
  const loadMore = () => {
    console.log('触发加载更多', { loading: loading.value, currentLength: questions.value.length, total: total.value })

    if (loading.value || questions.value.length >= total.value) {
      console.log('跳过加载更多')
      return
    }

    page.value++
    console.log('开始加载第', page.value, '页')
    loadQuestions(true)
  }
  </script>

  <style lang="scss" scoped>
  .search-page {
    background-color: #f7f8fa;
    display: flex;
    flex-direction: column;
    height: 100vh;
  }

  // 搜索容器样式
  .search-container {
    margin-top: 10px;
    flex: 1;
    padding: 0 30rpx;

    .search-box {
      display: flex;
      align-items: center;
      background-color: #f3f4f6;
      border-radius: 50rpx;
      padding: 16rpx 24rpx;

      .search-icon {
        font-size: 32rpx;
        color: #9ca3af;
        margin-right: 16rpx;
      }

      .search-input {
        flex: 1;
        font-size: 28rpx;
        color: #374151;
        background: transparent;
        border: none;
        outline: none;
      }

      .clear-icon {
        font-size: 28rpx;
        color: #9ca3af;
        padding: 8rpx;
      }
    }
  }

  // 内容区域
  .content {
    padding: 0;
    flex: 1;
    height: 100%;
  }

  // 搜索结果统计
  .search-result-info {
    margin-bottom: 24rpx;
    padding: 0 30rpx;
    display: flex;

    .result-count {
      font-size: 28rpx;
      color: #6b7280;
    }
  }

  // 热门搜索
  .hot-search {
    margin-bottom: 40rpx;
    padding: 0 30rpx;

    .section-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #1f2937;
      margin-bottom: 24rpx;
    }

    .hot-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 16rpx;

      .hot-tag {
        padding: 12rpx 24rpx;
        background-color: #f3f4f6;
        border-radius: 50rpx;
        font-size: 24rpx;
        color: #6b7280;

        &:active {
          background-color: #e5e7eb;
        }
      }
    }
  }

  // 题目列表
  .question-list {
    padding: 0 30rpx;

    .question-item {
      background-color: #fff;
      border-radius: 16rpx;
      padding: 32rpx;
      margin-bottom: 24rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
      position: relative;

      &:active {
        background-color: #f9fafb;
      }

      .vip-badge {
        position: absolute;
        top: 0;
        right: 0;
        width: 60rpx;
        height: 60rpx;
        z-index: 10;
        background: #ffd700;
        clip-path: polygon(0 0, 100% 0, 100% 100%);
        border-top-right-radius: 16rpx;

        &::after {
          content: 'VIP';
          position: absolute;
          top: 8rpx;
          right: 4rpx;
          color: #fff;
          font-size: 18rpx;
          font-weight: bold;
          transform: rotate(45deg);
          transform-origin: center;
        }
      }

      .question-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 24rpx;

        .question-title {
          flex: 1;
          font-size: 32rpx;
          font-weight: 500;
          color: #1f2937;
          line-height: 1.5;
          margin-right: 20rpx;
        }

        .question-meta {
          display: flex;
          align-items: center;
          gap: 16rpx;

          .difficulty-badge {
            padding: 4rpx 12rpx;
            border-radius: 12rpx;
            font-size: 20rpx;
            font-weight: 500;

            &.difficulty-1 {
              background-color: #dcfce7;
              color: #16a34a;
            }

            &.difficulty-2 {
              background-color: #fef3c7;
              color: #d97706;
            }

            &.difficulty-3 {
              background-color: #fee2e2;
              color: #dc2626;
            }

            &.difficulty-4 {
              background-color: #f1f5f9;
              color: #64748b;
            }
          }

          .publish-date {
            font-size: 24rpx;
            color: #9ca3af;
          }
        }
      }

      .question-stats {
        display: flex;
        gap: 32rpx;
        justify-content: space-between;

        .question-stats-right {
          display: flex;
          align-items: center;
          gap: 32rpx;
        }

        .stat-item {
          display: flex;
          align-items: center;
          gap: 8rpx;

          .stat-icon {
            font-size: 24rpx;
          }

          .stat-text {
            font-size: 24rpx;
            color: #6b7280;
          }
        }
      }
    }
  }

  // 空状态
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 120rpx 0;

    .empty-icon {
      font-size: 120rpx;
      margin-bottom: 32rpx;
    }

    .empty-text {
      font-size: 32rpx;
      color: #6b7280;
      margin-bottom: 16rpx;
    }

    .empty-desc {
      font-size: 28rpx;
      color: #9ca3af;
    }
  }

  // 加载更多
  .load-more,
  .no-more {
    text-align: center;
    padding: 40rpx 0;

    .load-more-text,
    .no-more-text {
      font-size: 28rpx;
      color: #9ca3af;
    }
  }

  // 状态激活样式
  .stat-item.active {
    .stat-text {
      color: #ef4444;
    }
  }
  </style>